package giermala.dominik.fotka.dao;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

public abstract class AbstractJpaDao<T extends Serializable> {

	private Class<T> clazz;

	@PersistenceContext
	EntityManager entityManager;

	public void setClazz(final Class<T> clazzToSet) {
		this.clazz = clazzToSet;
	}

	public T findById(final Long id) {
		return entityManager.find(clazz, id);
	}

	public List<T> findAll() {
		TypedQuery<T> query = entityManager.createQuery("from " + clazz.getName(), clazz);
		return query.getResultList();
	}

	public void save(final T entity) {
		entityManager.persist(entity);
	}

	public void update(final T entity) {
		entityManager.merge(entity);
	}

	public void delete(final T entity) {
		entityManager.remove(entity);
	}

	public void deleteById(final Long entityId) {
		final T entity = findById(entityId);

		delete(entity);
	}
}